//
//  XUserAccount.swift
//  WeiBoReDo
//
//  Created by 放学跟鸽走 on 2017/4/9.
//  Copyright © 2017年 放学跟鸽走. All rights reserved.
//

import UIKit
private let accountFile: NSString = "useraccount.json"
/// 登录用户模型
class XUserAccount: NSObject {
    //            "access_token" = "2.00HeA54GtJX7YEcbe16ed3460eS2v8";
    //用户授权的唯一票据，用于调用微博的开放接口，
    //同时也是第三方应用验证微博用户登录的唯一票据，
    //第三方应用应该用该票据和自己应用内的用户建立唯一影射关系，来识别登录状态，
    //不能使用本返回值里的UID字段来做登录识别。
    var access_token:String?
    //"expires_in" = 157679999;
    //access_token的生命周期，单位是秒数。
    var expires_in:TimeInterval = 0{
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    //过期日期
    var expiresDate:Date?
    //用户昵称
    var screen_name:String?
    //用户头像地址（大图），180×180像素
    var avatar_large :String?
    
    var uid:String?
    //            uid = 5842375079;
    override var description: String{
        return self.yy_modelDescription()
    }
    
    func saveAccount(){
        //先转成字典，把expires_in去掉
        var dict = yy_modelToJSONObject() as? [String:Any]
        dict?.removeValue(forKey: "expires_in")
        let data = try? JSONSerialization.data(withJSONObject: dict ?? [:], options: [])
        
        let path = accountFile.cz_appendDocumentDir() ?? ""
        try? data?.write(to: URL(fileURLWithPath: path), options: [])
        
        
    }
    override init() {
        super.init()
        //文件保存的路径
        guard let path = accountFile.cz_appendDocumentDir(),
        //读取文件，得到data
        let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
        //反序列化得到字典
        let dict = try? JSONSerialization.jsonObject(with: data, options: [])
        else{
            return
        }
        //字典转模型
        yy_modelSet(withJSON: dict)
        
        //判断是否过期
        if expiresDate?.compare(Date()) != .orderedDescending{
            //token过期，清除保存的用户对象
            access_token = nil
            uid = nil
            try? FileManager.default.removeItem(atPath: path)
        }
    }
}
